#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <stdio.h>

#include "Snake.h"
#include "Apple.h"
#include "Screen.h"

struct Gameplay {
	Screen* screen;
	Snake* snake;
	Apple* apple;
	bool lock;
};

//linuksowy getch ;]
int getch( ) {
	struct termios oldt, newt;
	int ch;

	tcgetattr( STDIN_FILENO, &oldt );

	newt = oldt;
	newt.c_lflag &= ~( ICANON | ECHO );

	tcsetattr( STDIN_FILENO, TCSANOW, &newt );
	ch = getchar();
	tcsetattr( STDIN_FILENO, TCSANOW, &oldt );

	return ch;
}

//watek do rysowania
void* print( void* arg ) {
	int points = 0;
	while( 1 ) {
		((Gameplay*)arg)->lock = true;
		((Gameplay*)arg)->screen->clear();
		((Gameplay*)arg)->screen->drawSnake( *((Gameplay*)arg)->snake );
		((Gameplay*)arg)->screen->drawApple( *((Gameplay*)arg)->apple );
		((Gameplay*)arg)->snake->move();

		if( ((Gameplay*)arg)->apple->check( *((Gameplay*)arg)->snake) ) {
			((Gameplay*)arg)->apple->choose();
			((Gameplay*)arg)->snake->add();
			points++;
		}

		((Gameplay*)arg)->screen->paint();

		printf("Punkty: %d\n", points);

		if( ((Gameplay*)arg)->screen->check(((Gameplay*)arg)->snake->getX(),((Gameplay*)arg)->snake->getY()) ){
			printf("Ales dojebal. %d punktow\n", points);
			exit(-1);
		}
		((Gameplay*)arg)->lock = false;
		usleep( 100000 );


	}
	return NULL;
}

int main() {
	Gameplay g;
	Screen screen;
	Snake snake;
	Apple apple;

	g.snake = &snake;
	g.screen = &screen;
	g.apple = &apple;
	g.lock = false;

	pthread_t printThread;
	pthread_create( &printThread, NULL, print, &g );

	while(1) {
		char k = (char)getch();
		while( g.lock == true ) {}
		if( k == 'w' ) {
			snake.setDirection(Snake::U);
		} else if( k == 's' ) {
			snake.setDirection(Snake::D);
		} else if( k == 'a' ) {
			snake.setDirection(Snake::L);
		} else if( k == 'd' ) {
			snake.setDirection(Snake::R);
		}
		g.lock = true;
	}

	pthread_join ( printThread, NULL );

	return 0;
}

